<template>
  <div class="login-index">
    <van-nav-bar
        title="注册/登录"
        left-arrow
        @click-left="$router.back()"
        class="app-nav-bar"
    />
    <van-form @submit="onLogin"
              ref="login-form"
              :show-error="false"
              :show-error-message="false"
              @failed="onFailed">
      <van-field
          v-model="user.mobile"
          size="small"
          placeholder="请输入手机号"
          name="mobile"
          left-icon="phone-circle-o"
          right-icon="warning-o"
          :rules="formRules.mobile"

      />
      <van-field
          v-model="user.code"
          clearable
          placeholder="请输入验证码"
          name="code"
          left-icon="music-o"
          :rules="formRules.code"
      >
      <template #button>
        <van-count-down
            v-if=" isCountDownShow"
            :time="1000*60"
            format="ss s"
            @finish="isCountDownShow=false"/>
        <van-button
            v-else
            size="small"
            round
            type="info"
            @click.prevent="onSendSms">发送验证码</van-button>
      </template>
      </van-field>

    <van-button
        type="info"
        block>登录</van-button>
    </van-form>
  </div>

</template>

<script>
import {login,sendSms} from "@/api/user";

export default {
  name: "index",
  data(){
    return{
      user:{
        mobile:'17090086870',
        code:'246810'
      },
      formRules:{
        mobile:[
          {required:true,message:'请输入手机号'},
          {pattern:/^1[3|5|7|9]\d{9}$/,message: '手机号格式错误'}
        ],
        code:[
          {required:true,message:'请输入验证码'},
          {pattern:/^\d{6}$/,message: '验证码格式错误'}
        ]
      },
      isCountDownShow:false
    }
  },
  methods:{
   async onLogin(){
     this.$toast.loading({
       message: '加载中...',
       forbidClick: true,
     })
     try {
      const {data}=await login(this.user)
       this.$toast.success('登录成功')
       this.$store.commit('setUser',data.data)
       this.$router.push('/my')
     }catch (err){
       console.log(err);
       this.$toast.fail('登录失败，手机号或验证码错误')
     }
   },
    onFailed(error){
      if (error.errors[0]){
        this.$toast({
          message:error.errors[0].message,
          position:"top"
        })
     }
    },
   async onSendSms(){
     try {
      await this.$refs['login-form'].validate('mobile')
      const res=await sendSms(this.user.mobile)
       this.isCountDownShow=true

     } catch (err){
       let message=''
       if (err && err.res && res.response.status===429){
         message='发送太频繁，请稍后重试'
       }else if (err.name==='mobile'){
         message=err.message
       }else {
         message='发送失败，请稍后重试'
       }
       this.$toast({
         message,
         position:"top"
       })
     }
    }
  }
}
</script>

<style scoped>

</style>